import 'dart:io';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wallpaper/components/AlertDialog/loading_dialog.dart';
import 'package:wallpaper/components/button/action_icon_btn.dart';
import 'package:wallpaper/components/button/normal_button.dart';
import 'package:wallpaper/generated/l10n.dart';
import 'package:wallpaper_manager_plus/wallpaper_manager_plus.dart';

// ignore: must_be_immutable
class LocalImageView extends StatefulWidget {
  final List images;
  int selectedIndex;
  LocalImageView({
    super.key,
    required this.images,
    required this.selectedIndex,
  });

  @override
  State<LocalImageView> createState() => _LocalImageViewState();
}

class _LocalImageViewState extends State<LocalImageView> {
  bool isLove = false;
  double iconSize = 30;
  late PageController _pageController;
  bool isOperation = true;

  Future<void> setWallpaper() async {
    // 弹出壁纸类型选择对话框
    final int? location = await showDialog<int>(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.black.withOpacity(0.7),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        elevation: 6,
        shadowColor: Colors.black26,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildListTitle(
                  S.of(context).b1, S.of(context).b2, Icons.phone_android, () {
                Navigator.pop(context, WallpaperManagerPlus.homeScreen);
              }),
              _buildListTitle(
                  S.of(context).b3, S.of(context).b4, Icons.lock_rounded, () {
                Navigator.pop(context, WallpaperManagerPlus.lockScreen);
              }),
              _buildListTitle(
                  S.of(context).b5, S.of(context).b6, Icons.phonelink_setup,
                  () {
                Navigator.pop(context, WallpaperManagerPlus.bothScreens);
              }),
              NormalButton(
                title: S.of(context).b7,
                onPressed: () {
                  Navigator.pop(context);
                },
                bgColor: const Color.fromARGB(60, 255, 255, 255),
              ),
            ],
          ),
        ),
      ),
    );

    if (location == null) return;
    var loadingClose = LoadingDialog.showLoading();
    try {
      await WallpaperManagerPlus()
          .setWallpaper(File(widget.images[widget.selectedIndex]), location);

      BotToast.showText(text: S.of(context).s4);
    } catch (e) {
      BotToast.showText(text: S.of(context).s5, contentColor: Colors.red);
    } finally {
      loadingClose();
    }
  }

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: widget.selectedIndex);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          color: Colors.black,
          // 导航栏字体颜色
          child: AnnotatedRegion<SystemUiOverlayStyle>(
            value: SystemUiOverlayStyle.light,
            child: Stack(
              children: [
                GestureDetector(
                  onTap: () {
                    setState(() {
                      isOperation = !isOperation;
                    });
                  },
                  child: PageView.builder(
                    controller: _pageController,
                    scrollDirection: Axis.vertical,
                    physics: const BouncingScrollPhysics(
                      parent: AlwaysScrollableScrollPhysics(),
                    ),
                    itemCount: widget.images.length,
                    itemBuilder: (context, index) =>
                        _buildImageView(widget.images[index]),
                    onPageChanged: (index) {
                      setState(() {
                        widget.selectedIndex = index;
                      });
                    },
                  ),
                ),
                Positioned(
                  top: 0,
                  right: 12,
                  bottom: 0,
                  child: Center(
                    child: AnimatedSlide(
                      offset: isOperation ? Offset.zero : const Offset(1.5, 0),
                      duration: const Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        spacing: 5,
                        children: [
                          ActionIconButton(
                            icon: Icons.phone_android_rounded,
                            onTap: setWallpaper,
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          )),
    );
  }

  Widget _buildImageView(String imagePath) {
    return Image.file(File(imagePath), fit: BoxFit.contain);
  }

  Widget _buildListTitle(
      String title, String subtitle, IconData icon, Function onTap) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 6),
      child: ListTile(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
        tileColor: Colors.white.withOpacity(0.07),
        title: Text(title,
            style: const TextStyle(
                color: Colors.white, fontWeight: FontWeight.bold)),
        subtitle: Text(subtitle,
            style: const TextStyle(color: Colors.white70, fontSize: 13)),
        leading: Icon(icon, color: Colors.white),
        trailing:
            const Icon(Icons.arrow_forward_ios, color: Colors.white, size: 18),
        onTap: () => onTap(),
      ),
    );
  }
}
